package com.mzj.saas.commons;

import com.mzj.saas.mservice.smartlock.vo.SmartLockApiHeaderVO;
import com.sun.net.ssl.internal.www.protocol.https.Handler;
import com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * SSLNet工具类
 * 
 * @author
 * @createTime
 * @history 1.修改时间,修改;修改内容：
 * 
 */
@Component
public class SSLNetProvider {

	private static final String UTF_8 = "UTF-8";
	private Logger LOG = LoggerFactory.getLogger(SSLNetProvider.class);

	private class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	/**
	 * doGet请求
	 * 
	 * @param url
	 * @return
	 * @throws WeixinException
	 */
	@SuppressWarnings("deprecation")
	public String doGet(String url) {
		LOG.debug("doGet url=" + url);
		InputStream in = null;
		HttpsURLConnectionOldImpl conn = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
			URL console = new URL(null, url, new Handler());
			conn = (HttpsURLConnectionOldImpl) console.openConnection();
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			in = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, UTF_8));
			String ret = null;
			StringBuilder strReturn = new StringBuilder();
			while ((ret = br.readLine()) != null) {
				strReturn.append(ret).append("\n");
			}
			LOG.debug("result=" + strReturn.toString());
			return strReturn.toString();
		} catch (ConnectException e) {
			LOG.error("ConnectException:", e);
			throw new CommonException("链接微信服务器失败");
		} catch (IOException e) {
			LOG.error("IOException:", e);
			throw new CommonException("从微信服务器读取数据失败");
		} catch (Exception e) {
			LOG.error("Exception:", e);
			throw new CommonException("从微信服务器读取数据失败");
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					LOG.error("Exception:", e);
				}
			}
			if (conn != null) {
				try {
					conn.disconnect();
				} catch (Exception e) {
					LOG.error("Exception", e);
				}
			}
		}
	}

	public String doGetTest(String url) throws CommonException {
		LOG.info("doGet url=" + url);
		InputStream in = null;
		HttpsURLConnectionOldImpl conn = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
			URL console = new URL(null, url, new Handler());
			conn = (HttpsURLConnectionOldImpl) console.openConnection();
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			in = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			String ret = null;
			String str_return = "";
			while ((ret = br.readLine()) != null) {
				str_return = str_return + ret + "\n";
			}
			LOG.info("result=" + str_return);
			return str_return;
		} catch (ConnectException e) {
			LOG.error("ConnectException:", e);
			throw new CommonException("链接微信服务器失败");
		} catch (IOException e) {
			LOG.error("IOException:", e);
			throw new CommonException("从微信服务器读取数据失败");
		} catch (Exception e) {
			LOG.error("Exception:", e);
			throw new CommonException("从微信服务器读取数据失败");
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					LOG.error("Exception:", e);
				}
			}
			if (conn != null) {
				try {
					conn.disconnect();
				} catch (Exception e) {
					LOG.error("Exception", e);
				}
			}
		}
	}

	/**
	 * doPost请求
	 * 
	 * @param url
	 * @param data
	 * @return
	 * @throws WeixinException
	 */
	@SuppressWarnings("deprecation")
	public String doPost(String url, String data) throws CommonException {
		LOG.info("doPost url=" + url);
		LOG.info("data=" + data);
		InputStream is = null;
		OutputStream out = null;
		HttpsURLConnectionOldImpl conn = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
			URL console = new URL(null, url, new Handler());
			conn = (HttpsURLConnectionOldImpl) console.openConnection();
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			out = conn.getOutputStream();
			DataOutputStream httpOut = new DataOutputStream(out);
			httpOut.write(data.getBytes(UTF_8));
			httpOut.flush();
			is = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, UTF_8));
			String ret = null;
			String str_return = "";
			while ((ret = br.readLine()) != null) {
				str_return = str_return + ret;
			}
			LOG.info("result=" + str_return);
			return str_return;
		} catch (ConnectException e) {
			LOG.error("Exception:" + e.getMessage(), e);
			throw new CommonException("服务器失败");
		} catch (IOException e) {
			LOG.error("Exception:" + e.getMessage(), e);
			throw new CommonException("服务器读取数据失败");
		} catch (Exception e) {
			LOG.error("Exception:" + e.getMessage(), e);
			throw new CommonException("服务器读取数据失败");
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					LOG.error("Exception:", e);
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					LOG.error("Exception:", e);
				}
			}
			if (conn != null) {
				try {
					conn.disconnect();
				} catch (Exception e) {
					LOG.error("Exception", e);
				}
			}
		}
	}

	/**
	 * doGet请求获取字节数组
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public byte[] doGetBytes(String url) throws CommonException {
		InputStream in = null;
		ByteArrayOutputStream outStream = null;
		HttpsURLConnectionOldImpl conn = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
			URL console = new URL(null, url, new Handler());
			conn = (HttpsURLConnectionOldImpl) console.openConnection();
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			in = conn.getInputStream();
			outStream = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int length = -1;
			while ((length = in.read(b, 0, 1024)) != -1) {
				outStream.write(b, 0, length);
			}
			return outStream.toByteArray();
		} catch (ConnectException e) {
			throw new CommonException("链接微信服务器失败");
		} catch (IOException e) {
			throw new CommonException("从微信服务器读取数据失败1");
		} catch (Exception e) {
			throw new CommonException("从微信服务器读取数据失败");
		} finally {
			if (outStream != null) {
				try {
					outStream.close();
				} catch (Exception e) {
					LOG.error(e.getMessage(), e);
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					LOG.error(e.getMessage(), e);
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	/**
	 * httpPost请求
	 * 
	 * @param url
	 * @param token
	 * @param data
	 * @return
	 */
	public String doHttpPost(String url, String token, String data) {
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
			httpPost.setHeader("Accept", "application/json");
			if (StringUtils.isNoneBlank(token)) {
				httpPost.setHeader("Authorization", "Bearer " + token);
			}
			httpPost.setEntity(new StringEntity(data, Charset.forName("UTF-8")));
			CloseableHttpClient createDefault = HttpClients.createDefault();
			CloseableHttpResponse result = createDefault.execute(httpPost);
			String responseMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
			LOG.info("responseMsg=" + responseMsg);
			return responseMsg;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}

	public String httpPost(String url, String json) throws Exception {
		LOG.info("url=" + url);
		LOG.info("json=" + json);
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		StringEntity postingString = new StringEntity(json, Charset.forName("UTF-8"));
		post.setEntity(postingString);
		post.setHeader("Content-type", "application/json");
		HttpResponse response = httpClient.execute(post);
		String content = EntityUtils.toString(response.getEntity());
		LOG.info("content=" + content);
		return content;
	}

	public String httpPostForm(String url, String json) throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		StringEntity postingString = new StringEntity(json, Charset.forName("UTF-8"));
		post.setEntity(postingString);
		post.setHeader("Content-type", "application/x-www-form-urlencoded");
		HttpResponse response = httpClient.execute(post);
		String content = EntityUtils.toString(response.getEntity());
		return content;
	}

	/**
	 * doGet请求
	 * 
	 * @param url
	 * @return
	 * @throws WeixinException
	 */
	@SuppressWarnings("deprecation")
	public String doGetAli(String url) {
		LOG.info("doGet url=" + url);
		InputStream in = null;
		HttpsURLConnectionOldImpl conn = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
			URL console = new URL(null, url, new Handler());
			conn = (HttpsURLConnectionOldImpl) console.openConnection();
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			in = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, UTF_8));
			String ret = null;
			StringBuilder strReturn = new StringBuilder();
			while ((ret = br.readLine()) != null) {
				strReturn.append(ret).append("\n");
			}
			LOG.info("result=" + strReturn.toString());
			return strReturn.toString();
		} catch (ConnectException e) {
			LOG.error("ConnectException:", e);
			throw new CommonException("检测广告填充失败");
		} catch (IOException e) {
			LOG.error("IOException:", e);
			throw new CommonException("读取广告填充读取失败");
		} catch (Exception e) {
			LOG.error("Exception:", e);
			throw new CommonException("读取广告填充数据失败");
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					LOG.error("Exception:", e);
				}
			}
			if (conn != null) {
				try {
					conn.disconnect();
				} catch (Exception e) {
					LOG.error("Exception", e);
				}
			}
		}
	}

	/**
	 * httpPost请求
	 * 
	 * @param url
	 * @param token
	 * @param data
	 * @return
	 */
	public String httpPost(String url, SmartLockApiHeaderVO vo, String data) {
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("SID", vo.getSid());
			httpPost.setHeader("X-Nonce", vo.getxNonce());
			httpPost.setHeader("X-Timestamp", vo.getxTimestamp());
			httpPost.setHeader("X-sign", vo.getxSign());

			if (StringUtils.isNotEmpty(data)) {
				httpPost.setEntity(new StringEntity(data, Charset.forName("UTF-8")));
			}

			CloseableHttpClient createDefault = HttpClients.createDefault();
			CloseableHttpResponse result = createDefault.execute(httpPost);
			String responseMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
			LOG.info("responseMsg=" + responseMsg);
			return responseMsg;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * httpGet请求
	 * 
	 * @param url
	 * @param token
	 * @return
	 */
	public String httpGet(String url, SmartLockApiHeaderVO vo) {
		try {
			HttpGet httpGet = new HttpGet(url);
			httpGet.addHeader("Content-type", "application/json; charset=utf-8");
			httpGet.setHeader("Accept", "application/json");
			httpGet.setHeader("SID", vo.getSid());
			httpGet.setHeader("X-Nonce", vo.getxNonce());
			httpGet.setHeader("X-Timestamp", vo.getxTimestamp());
			httpGet.setHeader("X-sign", vo.getxSign());

			CloseableHttpClient createDefault = HttpClients.createDefault();
			CloseableHttpResponse result = createDefault.execute(httpGet);
			String responseMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
			LOG.info("responseMsg=" + responseMsg);
			return responseMsg;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	
	/**
	 * httpPost请求
	 * 
	 * @param url
	 * @param token
	 * @param data
	 * @return
	 */
	public String httpPostYlt(String url, String data, String token) {
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
			httpPost.setHeader("Accept", "application/json");
			if(token != null){
				httpPost.setHeader("Authorization", token);
			}

			if (StringUtils.isNotEmpty(data)) {
				httpPost.setEntity(new StringEntity(data, Charset.forName("UTF-8")));
			}

			CloseableHttpClient createDefault = HttpClients.createDefault();
			CloseableHttpResponse result = createDefault.execute(httpPost);
			String responseMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
			LOG.info("responseMsg=" + responseMsg);
			return responseMsg;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
}
